import _ from 'lodash'
/* 处理提交保存的数据方法 */
export const getDealManageDataToApiFn = (data) => {
  /**
   @tableData 表格数据
   @type 页面类型，新增或者修改
   @notShowAttrList 表格不进行展示的字段集合
   @valueName 当前需要更改的值的名称，如果是新增，就是valueName，如果是修改，就是valueNameUpdate
   @uuidName 接口入参需要的id标识，如果是新增，就是productUuid，如果是修改，就是productKey
   @isEmptyItemNameList 必填项为空的集合，用来进行必填的校验提示
   @nameList 表格数据进行渲染的对应的对象名称集合
   @submitResults 接口入参需要的inputList参数value
  */
  let {
    tableData,
    type,
    notShowAttrList
  } = data
  let sourceTableList = _.cloneDeep(tableData)
  let valueName = type === 'add' ? 'valueName' : 'valueNameUpdate'
  let uuidName = type === 'add' ? 'productUuid' : 'productKey'
  let isEmptyItemNameList = new Set()
  let nameList = ['manageList', 'marketingList', 'taxList', 'logisticsList']
  let submitResults = _.cloneDeep(sourceTableList).reduce((value, item) => {
    let result = {
      [uuidName]: item.productUuid,
      spuNo: item.spuNo,
      thirdPlatList: item.thirdPlatList
    }
    if (type !== 'add') {
      result.authDepartments = item.authDepartments
    }
    nameList.forEach(nameType => {
      let attrList = item[nameType] && item[nameType].map(attrItem => {
        if (!notShowAttrList.includes(attrItem)) {
          let emptyFlag = _.isArray(item[attrItem][valueName]) ? item[attrItem][valueName].length === 0 : !item[attrItem][valueName]
          if (item[attrItem].attrMust === '1' && emptyFlag) {
            isEmptyItemNameList.add(item[attrItem].attrName)
          }
        }
        if (item[attrItem].attrType === '04') {
          item[attrItem][valueName] = item[attrItem][valueName] && item[attrItem][valueName].join(',')
        }
        return item[attrItem]
      })
      result[nameType] = attrList
    })
    value.push(result)
    return value
  }, [])
  let result = {
    submitResults
  }
  if (isEmptyItemNameList.size !== 0) {
    result.errorMessage = `${[...isEmptyItemNameList].join(',')}不能为空`
  }
  return result
}
